#pragma comment(lib, "Ws2_32.lib")
#include <WinSock2.h>
#include <iostream>
using namespace std;

int main() {
    cout<<"----------基于UDP的聊天程序----------"<<endl;
	cout<<"------服务器端开发（客户端先说）-----"<<endl;
	WORD wVersionRequested;
	WSADATA wsaData;
	wVersionRequested = MAKEWORD(2, 2);
	SOCKET ss;
	SOCKADDR_IN addrS;
	int len = sizeof(sockaddr);
	SOCKADDR_IN addrC;
	char recvBuf[128];
	char sendBuf[128];
	char tempBuf[128];
	if (WSAStartup(wVersionRequested, &wsaData) != 0) {
		cout<<"初始化DLL失败"<<endl;
		return 0;
	}
	ss = socket(AF_INET, SOCK_DGRAM, 0);
	addrS.sin_family = AF_INET;
	addrS.sin_port = htons(5000);
	addrS.sin_addr.s_addr = INADDR_ANY;
	bind(ss, (sockaddr *)&addrS, len);
	while (1) {
		recvfrom(ss, recvBuf, 128, 0, (sockaddr *)&addrC, &len);
		char *c_ip = inet_ntoa(addrC.sin_addr);
		sprintf (tempBuf, "%s说：%s\n", c_ip, recvBuf);
		cout<<tempBuf;
		gets(sendBuf);
		sendto(ss, sendBuf, strlen(sendBuf)+1, 0, (sockaddr *)&addrC, len);
	}
	closesocket(ss);
	WSACleanup();
	system("pause");
	return 0;
}